import {
	checkParams
} from "@/utils/tool/tool.js";
import {
	getToken,
	jumpLogin
} from "@/utils/token/token.js";

const baseUrl = "https://jxkjzylib.nccloudmedia.com/libsp"
const http = async ({
	url,
	method,
	data,
	errShow = true
}) => {
	// console.log(url);
	// wx.showLoading({
	//   title: '加载中...',
	// }) 
	return new Promise((resolve, reject) => {
		const token = getToken()
		uni.request({
			url: baseUrl + url,
			data: checkParams(data),
			method,
			header: {
				Authorization: 'Bearer ' + token,
			},
			success: ({
				data
			}) => success(data, resolve, reject, errShow),
			fail: (result) => fail(result, resolve, reject),
			complete: () => {
				uni.hideLoading({
					noConflict: true
				})
			}
		})
	})
}

const uploadHttp = ({
	url,
	filePath
}) => {
	// console.log('filePath', filePath);
	const token = getToken()
	uni.showLoading({
		title: '上传中...',
	})
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath,
			name: 'file',
			header: {
				Authorization: 'Bearer ' + token?.accessToken,
				'X-Authorization': 'Bearer ' + token?.refreshToken,
			},
			success: ({
				data
			}) => success(JSON.parse(data), resolve, reject),
			fail: (result) => fail(result, resolve, reject),
			complete: (res) => {
				// console.log('upload', res);
				uni.hideLoading({
					noConflict: true
				})
			}
		})
	})
}

function success(data, resolve, reject, errShow) {
	const s_code = data.errCode
	/* if ([200, 0, 9000065].includes(s_code)) {
		resolve(data.data)
		return;
	} */
	if (data.success) {
		resolve(data.data)
		return;
	}
	if (errShow) {
		if ([401].includes(s_code)) {
			// jumpLogin()
			uni.clearStorage()
			reject(data)
			return
		}
		uni.showToast({
			title: data.message,
			icon: 'none'
		})
		reject(data)
	} else {
		reject(data)
	}
}

function fail(result, resolve, reject) {
	/* const { errno = "", errCode = "", errMsg = "" } = result
	wx.showModal({
	  title: '服务端未响应',
	  content: `errno:${errno}\n
	            errCode:${errCode}\n
	            errMsg${errMsg}`,
	  confirmText: "上报异常",
	  complete: (res) => {
	    if (res.cancel) {
	    }
	    if (res.confirm) {
	    }
	  }
	}) */
	reject(result)
}

export const service = {
	get(url, data, errShow = true) {
		return http({
			url,
			method: 'GET',
			data,
			errShow
		})
	},
	post(url, data, errShow = true) {
		return http({
			url,
			method: 'POST',
			data,
			errShow
		})
	},
	upload(url, filePath, errShow = true) {
		return uploadHttp({
			url,
			filePath,
			errShow
		})
	},
	baseUrl,
}